<template>
  <div>
    <!-- 多条件查询 -->
    <el-form :inline="true">
      <el-form-item label="姓名">
        <el-input v-model="queryInfo.name" placeholder="请输入搜索姓名" clearable @clear="loadUsers"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable @clear="loadUsers"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryInfo.status" placeholder="全部" clearable @clear="loadUsers">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadUsers">查询</el-button>
        <el-button type="success" @click="addDialogVisible=true">添加</el-button>
        <el-button type="danger" @click="removeMultiple">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="userList" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="80"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="电话" prop="phone"></el-table-column>
      <el-table-column label="地址" prop="address"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" @change="modifyStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="removeById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.page"
      :page-sizes="[5, 10, 30]"
      :page-size="queryInfo.rows"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed">
      <el-form :rules="addFormRules" :model="addForm" ref="addFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" @close="editDialogClosed">
      <el-form :rules="editFormRules" :model="editForm" ref="editFormRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import qs from "qs";

export default {
  data() {
    return {
      // 查询的条件信息
      queryInfo: {
        page: 1,
        rows: 5,
        name: "",
        phone: "",
        status: null,
      },
      // 用户列表
      userList: [],
      // 总记录数
      total: 0,
      // 添加用户对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm:{},
      // 添加用户的表单验证规则
      addFormRules:{
        name:[
          {required:true,message:'请输入姓名',trigger:'blur'},
          {min:2,max:6,message:'长度在2-6个字符之间',trigger:'blur'}
        ],
        phone:[
          {required:true,message:'请输入电话',trigger:'blur'},
          {pattern:/^1[3456789]\d{9}$/,message:'电话格式不正确',trigger:'blur'}
        ],
        address:[
          {required:true,message:'请输入地址',trigger:'blur'}
        ]
      },
      editDialogVisible:false,
      editForm:{},
      editFormRules:{
        name:[
          {required:true,message:'请输入姓名',trigger:'blur'},
          {min:2,max:6,message:'长度在2-6个字符之间',trigger:'blur'}
        ],
        phone:[
          {required:true,message:'请输入电话',trigger:'blur'},
          {pattern:/^1[3456789]\d{9}$/,message:'电话格式不正确',trigger:'blur'}
        ],
        address:[
          {required:true,message:'请输入地址',trigger:'blur'}
        ]
      },
      // 多选框选中的数据
      multipleSelection:[]
    };
  },
  created() {
    this.loadUsers();
  },
  methods: {
    // 加载用户列表
    async loadUsers(flag) {
      // 如果flag不是true，就把页码设置为1，目的是只要是查询操作都从第一页开始查
      if (! Object.is(flag, true)) {
        this.queryInfo.page = 1;
      }

      const { data: res } = await this.$http.get("/user/findByCondition", {
        params: this.queryInfo,
      });
      this.userList = res.rows;
      this.userList.forEach((item) => {
        item.status = item.status === 1 ? true : false;
      });
      this.total = res.total;
    },
    // 根据id删除用户
    removeById(id) {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.get("/user/removeById?id=" + id);
          if (res.status != 1) {
            return this.$message.success("删除失败!");
          }
          this.$message.success("删除成功!");
          this.loadUsers();
        })
        .catch(() => {
          this.$message.info("取消删除!");
        });
    },
    // 监听页大小的改变
    handleSizeChange(val) {
      this.queryInfo.rows = val;
      this.loadUsers();
    },
    // 监听页码的改变
    handleCurrentChange(val) {
      this.queryInfo.page = val;
      this.loadUsers(true);
    },
    // 添加用户
    addUser(){
      // 先进行表单验证
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid){
          return;
        }
        // 表单验证通过，发送请求添加用户
        const {data:res} = await this.$http.post('/user/add', qs.stringify(this.addForm))
        if(res.status != 1){
          return this.$message.error('添加失败！')
        }
        // 提示添加成功
        this.$message.success('添加成功！')
        // 关闭对话框
        this.addDialogVisible = false;
        // 重新加载用户列表
        this.loadUsers();
      })
    },
    // 添加用户对话框关闭
    addDialogClosed(){
      // 清空表单数据
      this.$refs.addFormRef.resetFields();
    },
    // 显示修改用户的对话框
    async showEditDialog(id){
      const {data:res} = await this.$http.get(`/user/findById?id=${id}`)
      if(res.status != 1){
        return this.$message.error('获取用户信息失败！')
      }
      this.editForm = res.data;

      this.editDialogVisible = true;
    },
    // 修改用户对话框关闭
    editDialogClosed(){
      // 清空表单数据
      this.$refs.editFormRef.resetFields();
    },
    // 修改用户
    editUser(){
      // 先进行表单验证
      this.$refs.editFormRef.validate(async valid=>{
        if(!valid){
          return;
        }
        // 表单验证通过，发送请求修改用户
        const {data:res} = await this.$http.post('/user/modify', qs.stringify(this.editForm))
        if(res.status != 1){
          return this.$message.error('修改失败！')
        }
        // 提示修改成功
        this.$message.success('修改成功！')
        // 关闭对话框
        this.editDialogVisible = false;
        // 重新加载用户列表
        this.loadUsers();
      })
    },
    // 修改用户状态
    async modifyStatus(user){
      // 发送请求修改用户状态
      const {data:res} = await this.$http.get(`/user/modifyStatus`,{
        params:{
          id:user.id,
          status:user.status?1:0
        }
      })
      if(res.status != 1){
        return this.$message.error('修改状态失败！')
      }
      this.$message.success('修改状态成功！')
    },
    // 监听复选框的改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    removeMultiple(){
      new Promise((resolve)=>{
        this.multipleSelection.forEach(item => {
          this.$http.get(`/user/removeById?id=${item.id}`);
        })
        resolve()
      }).then(()=>{
        this.$message.success('批量删除成功！')
        this.loadUsers();
      })
    },
  },
};
</script>

<style lang="less" scoped>
.el-pagination{
  text-align: center;
}
</style>